import { usePageLoading } from '@/hooks/usePageLoading';
import { useAppStoreWithOut } from '@/store/modules/app';
import { usePermissionStoreWithOut } from '@/store/modules/permission';
import { useUserStoreWithOut } from '@/store/modules/user';

import router from './router';
import { NO_REDIRECT_WHITE_LIST } from './constants';

const { loadStart, loadDone } = usePageLoading();
router.beforeEach((to, from, next) => {
  loadStart();

  const permissionStore = usePermissionStoreWithOut();
  const appStore = useAppStoreWithOut();
  const userStore = useUserStoreWithOut();

  // 如果登录了
  if (userStore.userInfo) {
    if (to.path === '/login') {
      // 登录了，但是要去登录页，跳转到首页
      next({ path: '/' });
    } else {
      // 如果不是首页的话, 就看是否有权限路由
      if (permissionStore.routeInitCompleted) {
        next();
        return;
      }
    }
  } else {
    if (NO_REDIRECT_WHITE_LIST.includes(to.path)) {
      next();
    } else {
      next({ path: '/login', query: { redirect: to.fullPath } });
    }
  }
});

router.afterEach((to, from) => {
  loadDone();
});
